/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufg.inf.pos.bd;

import br.ufg.inf.pos.br.utils.ConnectionFactory;
import br.ufg.inf.pos.br.utils.RegraDaoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author luan
 */
public class CategoriaDaoImpl implements CategoriaDao {

    private Connection connection = null;
    private Statement statement = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;

    private final String COLUMN_NOME = "NOMECATEGORIA";
    private final String COLUMN_ID = "IDCATEGORIA";

    @Override
    public int salvar(Categoria categoria) {
        int codigoInserido = 0;

        try {
            connection = ConnectionFactory.getConnection();
            preparedStatement = connection
                    .prepareStatement("insert into categoria(" + COLUMN_NOME + ") values (?)", new String[]{COLUMN_ID});
            preparedStatement.setString(1, categoria.getCategoria());

            if (preparedStatement.executeUpdate() > 0) {
                resultSet = preparedStatement.getGeneratedKeys();
                if (null != resultSet && resultSet.next()) {
                    codigoInserido = resultSet.getInt(1);
                }
            }
        } catch (SQLException ex) {
            throw new RuntimeException("Erro ao recuperar objeto: "
                    + ex.getMessage());
        } finally {
            close();
            return codigoInserido;
        }

    }

    @Override
    public Categoria getByCode(int codCategoria, Connection conn) {
        Categoria categoriaLida = null;
        try {
            preparedStatement = conn
                    .prepareStatement("select * from categoria where categoria."
                            + COLUMN_ID + " = ? ");
            preparedStatement.setInt(1, codCategoria);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                categoriaLida = new Categoria();
                categoriaLida.setCategoria(resultSet.getString(COLUMN_NOME));
                categoriaLida.setCodigoCategoria(resultSet.getInt(COLUMN_ID));
            } else {
                throw new SQLException("Categoria não encontrada");
            }
        } catch (SQLException ex) {
            throw new RegraDaoException("Erro ao recuperar objeto: "
                    + ex.getMessage());
        } finally {
            return categoriaLida;
        }
    }

    @Override
    public Categoria getByName(String codCategoria) {
        Categoria categoriaLida = null;
        try {
            connection = ConnectionFactory.getConnection();
            preparedStatement = connection
                    .prepareStatement("select * from categoria where categoria."
                            + COLUMN_NOME + " = ? ");
            preparedStatement.setString(1, codCategoria);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                categoriaLida = new Categoria();
                categoriaLida.setCategoria(resultSet.getString(COLUMN_NOME));
                categoriaLida.setCodigoCategoria(resultSet.getInt(COLUMN_ID));
            } else {
                close();
                throw new RuntimeException("Categoria não encontrada");
            }
        } catch (SQLException ex) {
            throw new RuntimeException("Erro ao recuperar objeto: "
                    + ex.getMessage());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Erro ao conectar-se ao banco: "
                    + ex.getMessage());
        } finally {
            close();
            return categoriaLida;
        }
    }

    @Override
    public List<Categoria> getAll() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void atualizar(String nomeCategoria, Categoria categoria) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void remover(Categoria categoria) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public DefaultTableModel listarCategoriaJtable() {
        DefaultTableModel tabelaModelo = new DefaultTableModel();
        tabelaModelo.setColumnIdentifiers(new String[]{"Código Categoria", "Categoria"});
        int posicao = 0;
        try {
            connection = ConnectionFactory.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(
                    "select * from categoria order by categoria." + COLUMN_NOME + "");
            while (resultSet.next()) {
                tabelaModelo.insertRow(posicao, new Object[]{
                    resultSet.getString(COLUMN_ID), resultSet.getString(COLUMN_NOME)});
                posicao++;
            }
        } catch (SQLException ex) {
            throw new RuntimeException("Erro ao recuperar objeto: "
                    + ex.getMessage());
        } finally {
            close();
            return tabelaModelo;
        }
    }

// you need to close all three to make sure
    private void close() {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException("Erro ao fechar");
        }

    }

    @Override
    public List<Categoria> listarCaterogiasCombo() {

        List<Categoria> listaCategorias = new ArrayList<>();
        try {
            connection = ConnectionFactory.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(
                    "select * from categoria order by categoria." + COLUMN_NOME + "");
            while (resultSet.next()) {
                Categoria categoriaLida = new Categoria();
                categoriaLida.setCategoria(resultSet.getString(COLUMN_NOME));
                categoriaLida.setCodigoCategoria(resultSet.getInt(COLUMN_ID));
                listaCategorias.add(categoriaLida);
            }
        } catch (SQLException ex) {
            throw new RuntimeException("Erro ao recuperar objeto: "
                    + ex.getMessage());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Erro ao conectar-se ao banco: "
                    + ex.getMessage());
        } finally {
            close();
        }

        return listaCategorias;
    }

}
